package SA.teacher;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Calendar;
import SA.teacher.answer.AnswerActivity1;
import SA.teacher.daily.*;
import SA.teacher.manage.ManageActivity1;
import SA.teacher.notice.NoticeActivity1;
import SA.teacher.R;
import android.app.*;
import android.content.*;
import android.os.Bundle;
import android.util.Log;
import android.view.*;
import android.view.View.*;
import android.widget.*;

public class MainActivity extends Activity {
	String rcvclassid;
	static String id;
	String day = null;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		Intent intent = getIntent();
		id = intent.getStringExtra("ID");

		Calendar today = Calendar.getInstance();
		TextView todayDate = (TextView) findViewById(R.id.today);
		todayDate.setText((today.get(Calendar.MONTH) + 1) + "월"+ today.get(Calendar.DATE) + "일");

		int whatDay = today.get(Calendar.DAY_OF_WEEK);

		int tempday = whatDay % 7;
		switch (tempday) // 0~6까지 토~금요일로 표시
		{
		case 0:
			day = "토";
			break;
		case 1:
			day = "일";
			break;
		case 2:
			day = "월";
			break;
		case 3:
			day = "화";
			break;
		case 4:
			day = "수";
			break;
		case 5:
			day = "목";
			break;
		case 6:
			day = "금";
			break;
		}// end switch
									
		
		noticeparse ps = new noticeparse();
		ps.run();// 공지
		tscheduleparse tschps = new tscheduleparse();
		tschps.run();// 스케줄
		homeworkparse hwps = new homeworkparse();
		hwps.run();// 숙제
		classidparse cidps = new classidparse();
		cidps.run();
		//final String[] classes = rcvclassid.split(",");// 값들 받아오기

		// ////////////Button action////////////////////////////////////
		TextView noticeBtn = (TextView) findViewById(R.id.notice);
		noticeBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				noticeActivity();
			}
		});
		
		ImageView manageBtn = (ImageView) findViewById(R.id.manageBtn);
		manageBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				manageActivity();
			}
		});
		
		ImageView dailyBtn = (ImageView) findViewById(R.id.dailyBtn);
		dailyBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				dailyActivity();
			}
		});
		ImageView answerBtn = (ImageView) findViewById(R.id.answerBtn);
		answerBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				answerActivity();	
			}
		});
	}



	public class noticeparse implements Runnable {
		public void run() {

			// TODO Auto-generated method stub
			try {
				URL url = new URL("Http://220.67.128.8/noticeview.php");

				HttpURLConnection conn = (HttpURLConnection) url.openConnection();

				InputStream is = null;
				ByteArrayOutputStream baos = null;
				if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
					is = conn.getInputStream();
					baos = new ByteArrayOutputStream();
					byte[] byteBuffer = new byte[1024];
					byte[] byteData = null;
					int nLength = 0;
					while ((nLength = is.read(byteBuffer)) > 0) {
						baos.write(byteBuffer, 0, nLength);
					}
					byteData = baos.toByteArray();
					String response = new String(byteData, "euc-kr");
					if (response == null || response.equals("")) {
						throw new Exception("Response is NULL!");
					}
					TextView notice = (TextView) findViewById(R.id.notice);
					notice.setGravity(Gravity.CENTER);
					notice.setText(response);
				} else {
					Log.e("login 응답 : ", "접속 안됨");
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
			}
		}
	}

	private class tscheduleparse implements Runnable {
		public void run() {	Log.e("login 응답 : ","티처스케줄");
			// TODO Auto-generated method stub
			try {
				URL url = new URL("Http://220.67.128.8/teacherschedule.php?id="+ URLEncoder.encode(id, "EUC-KR") + "&day="+ URLEncoder.encode(day, "EUC-KR"));
				HttpURLConnection conn = (HttpURLConnection) url.openConnection();

				InputStream is = null;
				ByteArrayOutputStream baos = null;
				if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
					is = conn.getInputStream();
					baos = new ByteArrayOutputStream();
					byte[] byteBuffer = new byte[1024];
					byte[] byteData = null;
					int nLength = 0;
					while ((nLength = is.read(byteBuffer)) > 0) {
						baos.write(byteBuffer, 0, nLength);
					}
					byteData = baos.toByteArray();
					String response = new String(byteData, "euc-k-r");
					TextView scheduleText = (TextView) findViewById(R.id.scheduleText);
					scheduleText.setGravity(Gravity.CENTER);
					scheduleText.setText(response);
					if (response == null || response.equals("")) {
						throw new Exception("Response is NULL!");
					}
				} else {
					Log.e("login 응답 : ", "접속 안됨");
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
			}
		}
	}


	private class classidparse implements Runnable {
		public void run() {	//Log.e("login 응답 : ", id);
		//Log.e("login 응답 : ", day);
			// TODO Auto-generated method stub
			try {
				URL url = new URL("Http://220.67.128.8/dayclassid.php?id="+ URLEncoder.encode(id, "EUC-KR") + "&day="+ URLEncoder.encode(day, "EUC-KR"));

				HttpURLConnection conn = (HttpURLConnection) url.openConnection();

				InputStream is = null;
				ByteArrayOutputStream baos = null;
				if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
					is = conn.getInputStream();
					baos = new ByteArrayOutputStream();
					byte[] byteBuffer = new byte[1024];
					byte[] byteData = null;
					int nLength = 0;
					while ((nLength = is.read(byteBuffer)) > 0) {
						baos.write(byteBuffer, 0, nLength);
					}
					byteData = baos.toByteArray();
					String response = new String(byteData, "euc-k-r");
					rcvclassid = response;
					if (response == null || response.equals("")) {
						throw new Exception("Response is NULL!");
					}
				} else {
					Log.e("login 응답 : ", "접속 안됨");
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
			}
		}
	}

	public class homeworkparse implements Runnable {
		public void run() {

			// TODO Auto-generated method stub
			try {
				URL url = new URL("Http://220.67.128.8/homeworkview.php?id="+ URLEncoder.encode(id, "EUC-KR"));
				
				HttpURLConnection conn = (HttpURLConnection) url.openConnection();

				InputStream is = null;
				ByteArrayOutputStream baos = null;
				if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
					is = conn.getInputStream();
					baos = new ByteArrayOutputStream();
					byte[] byteBuffer = new byte[1024];
					byte[] byteData = null;
					int nLength = 0;
					while ((nLength = is.read(byteBuffer)) > 0) {
						baos.write(byteBuffer, 0, nLength);
					}
					byteData = baos.toByteArray();
					String response = new String(byteData, "euc-kr");
					if (response == null || response.equals("")) {
						throw new Exception("Response is NULL!");
					}
					TextView hwText = (TextView) findViewById(R.id.hwText);
					hwText.setGravity(Gravity.CENTER);
					hwText.setText(response);
				} else {
					Log.e("login 응답 : ", "접속 안됨");
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
			}
		}
	}
	//////////////Button 함수들////////////////////////////////////
	void noticeActivity() {
		Intent intent = new Intent(this, NoticeActivity1.class);
		intent.putExtra("ID",id);
		startActivity(intent);
	}

	void manageActivity() {
		classidparse cidps = new classidparse();
		cidps.run();
		final String[] classes = rcvclassid.split(",");
		if(classes.length-1!=0){
			new AlertDialog.Builder(MainActivity.this)
			.setTitle("반을 선택해주세요.")
			.setItems(classes, new DialogInterface.OnClickListener() {

				public void onClick(DialogInterface dialog,	int which) {
					Intent intent = new Intent(MainActivity.this, ManageActivity1.class);
					intent.putExtra("ID",id);
					intent.putExtra("classname",classes[which]);
					startActivity(intent);
				}
			}).show();
		}
		else{
			new AlertDialog.Builder(MainActivity.this)
			.setMessage("현재 담당하는 반이 없습니다.")
			.setPositiveButton("확인", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
					// TODO Auto-generated method stub
				}
			}).show();
		}
	}
	void dailyActivity() {
		Intent intent = new Intent(this, DailyActivity1.class);
		intent.putExtra("ID",id);
		startActivity(intent);
	}
	void answerActivity() {
		Intent intent = new Intent(this, AnswerActivity1.class);
		intent.putExtra("ID",id);
		startActivity(intent);
	}
	
	//////////////뒤로가기 버튼 종료////////////////////////////////////
	public boolean onKeyDown(int keyCode, KeyEvent event){
		switch(keyCode){
		case KeyEvent.KEYCODE_BACK:
			String alertTitle = getResources().getString(R.string.app_name);
			String buttonMessage = getResources().getString(R.string.alert_msg_exit);
			String buttonYes = getResources().getString(R.string.button_yes);
			String buttonNo = getResources().getString(R.string.button_no);

			new AlertDialog.Builder(MainActivity.this)
			.setTitle(alertTitle)
			.setMessage(buttonMessage)
			.setPositiveButton(buttonYes, new DialogInterface.OnClickListener() {

				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					moveTaskToBack(true);
					finish();
				}
			})
			.setNegativeButton(buttonNo, null)
			.show();
		}
		return true;
	}

}
